<template>
	<coreshop-page title="提现" mode="left">
		<view class="box" v-if="shopConfigStore.config.isAllowWithdrawCash === AllowWithdrawCashEnum.yes">
			<view class="card">
				<view class="select-bank" v-if="Object.keys(state.defaultBankCard).length > 0"
					@click="onRedirectBankCard()">
					<view class="card-box">
						<image class="bank-logo" :src="state.defaultBankCard.bankLogo" mode="widthFix"> </image>
						<view class="card-num">
							{{state.defaultBankCard?.cardNumber}}
						</view>
					</view>
					<uv-icon name="arrow-right"></uv-icon>
				</view>
				<view v-else class="select-bank" @click="onRedirectBankCard()">
					<view class="add-card">请选择提现银行卡</view>
					<uv-icon name="arrow-right"></uv-icon>
				</view>
				<view class="tip" v-if="tocashExplain">{{tocashExplain}}</view>
				<view class="input-withdraw">
					<uv-input border="none" v-model="state.money" placeholder="请输入提现金额" type="number"
						clearable></uv-input>
				</view>
				<view class="balance" v-if="state.money <= state.maxMoney">
					<view class="used m-b-20">可用余额：<text class="money">￥{{state.userInfo?.balance}}</text></view>
					<view class="max_withdraw">扣除手续费最高可提现￥{{state.maxMoney.toFixed(2)}}</view>
				</view>
				<view class="balance-tip" v-else>提现金额超过最高可提现金额</view>
			</view>
			<view class="msg-box">
				<view class="lab">提现须知：</view>
				<view class="val">1、提现金额加提现服务费需超过或等于余额；</view>
				<view class="val">2、充值一经办理，概不退款；</view>
			</view>
		</view>
		<view v-else class="layout-empty-box">
			<coreshop-empty :mode="EmptyEnum.data" text="暂未开启提现功能"></coreshop-empty>
		</view>

		<coreshop-fixed-bottom-button :radius="100" title="确认提现" @onClick="handletoCash"></coreshop-fixed-bottom-button>

	</coreshop-page>
</template>

<script setup lang="ts">
	import { reactive, computed, watch } from 'vue';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import type { Response, UserInfoType, BankCardType } from '@/core/models';
	import { navigateTo, handleShowToast } from '@/core/utils';
	import { queryUserInfo, queryDefaultBankCard, queryUserToCash } from '@/core/api';
	import { useShopConfigStore } from '@/core/store';
	import { AllowWithdrawCashEnum, EmptyEnum } from '@/core/enum';
	import { selectBankCard } from '@/core/consts';

	// 获取项目配置
	const shopConfigStore : any = useShopConfigStore();

	const state = reactive<{
		userInfo : UserInfoType;
		defaultBankCard : BankCardType;
		maxMoney : number;
		money : number | null;
		submitStatus : boolean;
	}>({
		userInfo: {},
		defaultBankCard: {},
		maxMoney: 0,
		money: null,
		submitStatus: true,
	})

	onLoad(() => {
		getUserInfo();
	});

	onShow(() => {
		if (uni.getStorageSync(selectBankCard)) {
			state.defaultBankCard = uni.getStorageSync(selectBankCard);
		} else {
			getDefaultBankCard();
		}
	});

	const tocashExplain = computed(() => {
		if (shopConfigStore.config?.toCashMoneyRate && shopConfigStore.config?.toCashMoneyLow) {
			return `最低提现金额${shopConfigStore.config?.toCashMoneyLow}元（收取${shopConfigStore.config?.toCashMoneyRate}%服务费）`;
		} else if (shopConfigStore.config?.toCashMoneyRate) {
			return `收取${shopConfigStore.config?.toCashMoneyRate}%服务费`;
		} else if (shopConfigStore.config?.toCashMoneyLow) {
			return `最低提现金额${shopConfigStore.config?.toCashMoneyLow}元`;
		} else {
			return '';
		}
	});

	/** 获取用户信息 */
	const getUserInfo = async () => {
		const userInfo : Response<UserInfoType> = await queryUserInfo();
		state.userInfo = userInfo?.data;
		state.maxMoney = (state.userInfo.balance * 10000 - state.userInfo.balance * Number(shopConfigStore.config.toCashMoneyRate) / 100 * 10000) / 10000;
	}

	/** 获取默认银行卡 */
	const getDefaultBankCard = async () => {
		const defaultBankCard : Response<BankCardType> = await queryDefaultBankCard();
		if (defaultBankCard.status) {
			state.defaultBankCard = defaultBankCard.data;
		}
	}

	const onRedirectBankCard = () => {
		navigateTo({ url: `/pages/subpackage/member/balance/bank-card/index?type='select'` });
	}

	/** 去提现 */
	const handletoCash = async () => {
		if (!state.submitStatus) {
			return;
		} else if (Object.keys(state.defaultBankCard).length == 0) {
			handleShowToast('请选择要提现的银行卡'); return;
		} else if (state.money == 0) {
			handleShowToast('提现金额不能为0'); return;
		} else if (!state.money) {
			handleShowToast('请输入要提现的金额'); return;
		} else if (state.money > state.maxMoney) {
			handleShowToast('提现金额不可超过最高可提现金额'); return;
		}
		state.submitStatus = true;
		const userToCash : Response<any> = await queryUserToCash({
			data: state.money,
			id: state.defaultBankCard.id
		});
		if (userToCash.status) {
			state.submitStatus = false;
			handleShowToast(userToCash.msg, 'success', () => {
				uni.navigateBack();
			});
		} else {
			state.submitStatus = false;
			handleShowToast(userToCash.msg);
		}
	}
</script>

<style scoped lang="scss">
	@import './index.scss';
</style>